package common

import (
	"encoding/json"
	"fmt"
	"net"
)

type ConnManager struct {
	conn net.Conn
}

func NewConnManager(conn net.Conn) *ConnManager {
	return &ConnManager{
		conn: conn,
	}
}

func (manager *ConnManager) ResponseString(msg string, sType string) {
	subMessage := ResponseString{
		Content: msg,
	}
	manager.ResponseStruct(subMessage, sType)
}

func (manager *ConnManager) ResponseStruct(subMessage interface{}, sType string) {
	buffer, err := json.Marshal(subMessage)
	if err != nil {
		fmt.Println("信息编码失败, err=", err)
		return
	}
	response := Response{
		Data: string(buffer),
		Code: sType,
	}
	buffer, err = json.Marshal(response)
	if err != nil {
		fmt.Println("信息编码失败, err=", err)
		return
	}
	i, err := manager.conn.Write(buffer)
	if err != nil || i != len(buffer) {
		fmt.Println("返回给客户端数据异常, err=", string(buffer))
	}
	fmt.Printf("\n返回客户端的数据为:%v\n", string(buffer[:i]))
}

func (manager *ConnManager) RequestStruct(subMessage interface{}, sType string) {
	buffer, err := json.Marshal(subMessage)
	if err != nil {
		fmt.Println("信息编码失败, err=", err)
		return
	}
	message := Request{
		Data: string(buffer),
		Type: sType,
	}
	buffer, err = json.Marshal(message)
	if err != nil {
		fmt.Println("信息编码失败, err=", err)
		return
	}
	i, err := manager.conn.Write(buffer)
	if err != nil || i != len(buffer) {
		fmt.Println("信息发送失败, err=", err)
		return
	}
	fmt.Printf("\n发给服务端的数据为:%v\n", string(buffer[:i]))
	return
}
